<template>
  <div class="table-indexes-panel">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-sm font-medium text-gray-700">索引定义</h3>
      <div class="flex space-x-2">
        <el-button size="small" @click="addIndex" type="success" plain class="hover:bg-green-50 transition-colors">
          <el-icon><Plus /></el-icon>添加索引
        </el-button>
      </div>
    </div>

    <div v-if="columns.length === 0" class="text-center py-8 bg-gray-50 rounded-lg border border-gray-200 shadow-sm">
      <p class="text-gray-500">请先添加表列，然后再创建索引</p>
    </div>
    <div v-else-if="indexes.length === 0" class="text-center py-8 bg-gray-50 rounded-lg border border-gray-200 shadow-sm">
      <p class="text-gray-500">该表没有索引</p>
      <el-button size="small" type="primary" class="mt-4 hover:bg-blue-600 transition-colors" @click="addIndex">创建索引</el-button>
    </div>
    <div v-else class="overflow-x-auto rounded-lg shadow-sm border border-gray-200">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">索引名</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">类型</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">列</th>
            <th scope="col" class="w-10 px-3 py-3 text-left"></th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(index, idx) in localIndexes" :key="idx" class="hover:bg-gray-50 transition-colors">
            <td class="px-3 py-3">
              <el-input v-model="index.name" size="small" placeholder="索引名" @change="handleIndexesChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all" />
            </td>
            <td class="px-3 py-3">
              <el-select v-model="index.type" size="small" style="width: 100%" @change="handleIndexesChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all">
                <el-option 
                  v-for="option in indexTypeOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </td>
            <td class="px-3 py-3">
              <el-select 
                v-model="index.columns" 
                size="small" 
                style="width: 100%" 
                multiple 
                filterable 
                placeholder="选择列" 
                @change="handleIndexesChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
              >
                <el-option 
                  v-for="column in columns" 
                  :key="column.name" 
                  :label="column.name" 
                  :value="column.name" 
                />
              </el-select>
            </td>
            <td class="px-3 py-3">
              <el-button 
                type="danger" 
                size="small" 
                circle 
                plain
                @click="confirmRemoveIndex(idx)"
                class="hover:bg-red-50 transition-colors"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';

const props = defineProps({
  indexes: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    default: () => []
  },
  databaseType: {
    type: String,
    default: 'mysql'
  }
});

const emit = defineEmits(['update', 'add', 'remove']);

const localIndexes = ref([...props.indexes]);

// 监听props变化
watch(() => props.indexes, (newIndexes) => {
  localIndexes.value = [...newIndexes];
}, { deep: true });

// 根据数据库类型获取可用的索引类型
const indexTypeOptions = computed(() => {
  const commonTypes = [
    { label: '普通索引', value: 'INDEX' },
    { label: '唯一索引', value: 'UNIQUE' }
  ];
  
  switch (props.databaseType) {
    case 'mysql':
      return [
        ...commonTypes,
        { label: '全文索引', value: 'FULLTEXT' },
        { label: '空间索引', value: 'SPATIAL' }
      ];
    case 'postgresql':
      return [
        ...commonTypes,
        { label: '哈希索引', value: 'HASH' },
        { label: 'GIN索引', value: 'GIN' },
        { label: 'GIST索引', value: 'GIST' },
        { label: 'BRIN索引', value: 'BRIN' }
      ];
    case 'sqlserver':
      return [
        ...commonTypes,
        { label: '聚集索引', value: 'CLUSTERED' },
        { label: '非聚集索引', value: 'NONCLUSTERED' },
        { label: '唯一聚集', value: 'UNIQUE_CLUSTERED' },
        { label: '唯一非聚集', value: 'UNIQUE_NONCLUSTERED' }
      ];
    default:
      return commonTypes;
  }
});

// 添加索引
const addIndex = () => {
  if (props.columns.length === 0) {
    ElMessageBox.alert('请先添加表列，然后再创建索引', '提示', {
      confirmButtonText: '确定'
    });
    return;
  }
  
  // 生成默认索引名
  const indexName = generateIndexName();
  
  // 创建新索引
  const newIndex = {
    name: indexName,
    type: 'INDEX',
    columns: []
  };
  
  // 添加到本地索引
  localIndexes.value.push(newIndex);
  
  // 发送添加事件
  emit('add', newIndex);
};

// 生成索引名
const generateIndexName = () => {
  const existingNames = localIndexes.value.map(idx => idx.name);
  let i = 1;
  let baseName = props.databaseType === 'sqlserver' ? 'IX_' : 'idx_';
  let name = `${baseName}${i}`;
  
  while (existingNames.includes(name)) {
    i++;
    name = `${baseName}${i}`;
  }
  
  return name;
};

// 确认删除索引
const confirmRemoveIndex = (index) => {
  const indexName = localIndexes.value[index].name || `索引 #${index + 1}`;
  
  ElMessageBox.confirm(`确定要删除索引 "${indexName}" 吗?`, '确认删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 发送删除事件
    emit('remove', index);
  }).catch(() => {
    // 用户取消操作
  });
};

// 发送索引变更事件
const handleIndexesChange = () => {
  emit('update', [...localIndexes.value]);
};
</script>

<style scoped>
.table-indexes-panel {
  padding: 16px 0;
}

:deep(.el-input__wrapper) {
  @apply shadow-none;
}

:deep(.el-input__wrapper:hover) {
  @apply border-gray-400;
}

:deep(.el-input__wrapper.is-focus) {
  @apply border-blue-500 ring-1 ring-blue-500;
}

:deep(.el-select .el-input__wrapper) {
  @apply shadow-none;
}

:deep(.el-select-dropdown__item) {
  @apply text-sm py-2;
}

:deep(.el-tag) {
  @apply text-xs bg-blue-50 border-blue-100 text-blue-600;
}

:deep(.el-tag .el-tag__close) {
  @apply text-blue-400 hover:bg-blue-500 hover:text-white;
}
</style> 